package logic

import (
	"context"
	"fmt"
	"user/model/cache"
	"user/model/mysql"
	"user/userrpc/internal/svc"
	"user/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	s, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Mobile).Result()
	if s != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误，请重新输入")
	}

	var user mysql.User
	mysql.DB.Debug().Where("mobile" + in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("当前账号未注册，请重新登陆")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}
	return &userrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
